<template>
  <div class="admin-layout">
    <div class="layout-container">
      <!-- 左侧菜单栏 -->
      <aside :class="['sidebar', { 'collapsed': sidebarCollapsed }]">
        <div class="toggle-btn" @click="toggleSidebar">
          <span>{{ sidebarCollapsed ? '›' : '‹' }}</span>
        </div>

        <nav class="menu-nav" v-show="!sidebarCollapsed">
          <ul>
            <template v-for="menu in userMenus" :key="menu.menuId">
              <li v-if="menu.menuId === 'admin_root' || menu.menuId === 'teacher_root' || menu.menuId === 'parent_root' || menu.menuId === 'assistant_root'">
                <!-- 根级菜单标题，不展开 -->
                <div class="root-menu-title">
                  <span class="menu-icon">{{ getIconUnicode(menu.menuIcon) }}</span>
                  <span class="menu-text">{{ menu.menuName }}</span>
                </div>
                <!-- 显示根菜单的所有子菜单（即一级分类） -->
                <ul class="submenu" v-if="menu.children && menu.children.length > 0">
                  <template v-for="submenu in menu.children" :key="submenu.menuId">
                    <li v-if="!submenu.children || submenu.children.length === 0">
                      <!-- 没有子菜单的直接项 -->
                      <a
                        href="#"
                        class="menu-item"
                        :class="{ active: isActiveMenu(submenu.menuUrl) }"
                        @click.prevent="handleMenuClick(submenu)"
                      >
                        <span class="menu-icon">{{ getIconUnicode(submenu.menuIcon) }}</span>
                        <span class="menu-text">{{ submenu.menuName }}</span>
                      </a>
                    </li>
                    <li v-else>
                      <!-- 一级分类（如"用户管理"） -->
                      <div class="menu-group">
                        <div class="menu-group-title" @click="toggleCategory(submenu.menuId)">
                          <span class="menu-icon">{{ getIconUnicode(submenu.menuIcon) }}</span>
                          <span class="menu-text">{{ submenu.menuName }}</span>
                          <span class="expand-icon" :class="{ expanded: isExpanded(submenu.menuId) }">▼</span>
                        </div>
                        <ul class="submenu" :class="{ hidden: !isExpanded(submenu.menuId) }">
                          <li v-for="subitem in submenu.children" :key="subitem.menuId">
                            <a
                              href="#"
                              class="menu-item"
                              :class="{ active: isActiveMenu(subitem.menuUrl) }"
                              @click.prevent="handleMenuClick(subitem)"
                            >
                              <span class="menu-icon">{{ getIconUnicode(subitem.menuIcon) }}</span>
                              <span class="menu-text">{{ subitem.menuName }}</span>
                            </a>
                          </li>
                        </ul>
                      </div>
                    </li>
                  </template>
                </ul>
              </li>
              <li v-else-if="!menu.children || menu.children.length === 0">
                <a
                  href="#"
                  class="menu-item"
                  :class="{ active: isActiveMenu(menu.menuUrl) }"
                  @click.prevent="handleMenuClick(menu)"
                >
                  <span class="menu-icon">{{ getIconUnicode(menu.menuIcon) }}</span>
                  <span class="menu-text">{{ menu.menuName }}</span>
                </a>
              </li>
              <li v-else>
                <!-- 非根菜单的分类项 -->
                <div class="menu-group">
                  <div class="menu-group-title" @click="toggleCategory(menu.menuId)">
                    <span class="menu-icon">{{ getIconUnicode(menu.menuIcon) }}</span>
                    <span class="menu-text">{{ menu.menuName }}</span>
                    <span class="expand-icon" :class="{ expanded: isExpanded(menu.menuId) }">▼</span>
                  </div>
                  <ul class="submenu" :class="{ hidden: !isExpanded(menu.menuId) }">
                    <li v-for="submenu in menu.children" :key="submenu.menuId">
                      <a
                        href="#"
                        class="menu-item"
                        :class="{ active: isActiveMenu(submenu.menuUrl) }"
                        @click.prevent="handleMenuClick(submenu)"
                      >
                        <span class="menu-icon">{{ getIconUnicode(submenu.menuIcon) }}</span>
                        <span class="menu-text">{{ submenu.menuName }}</span>
                      </a>
                    </li>
                  </ul>
                </div>
              </li>
            </template>
          </ul>
        </nav>
      </aside>

      <!-- 主内容区域 -->
      <main class="main-content">
        <!-- 标签页栏 -->
        <div class="tabs-bar">
          <div
            class="tab-item"
            :class="{ active: activeTab === '/admin' || activeTab === '/admin/dashboard' || activeTab === '/admin/home' || openedTabs.length === 0 }"
            @click="switchToDefaultTab"
          >
            <span>{{ $t('message.overview') }}</span>
            <!-- 默认标签不能关闭 -->
          </div>
          <div
            v-for="(tab, index) in openedTabs"
            :key="tab.name"
            class="tab-item"
            :class="{ active: activeTab === tab.name }"
            @click="switchTab(tab.name)"
          >
            <span>{{ tab.title }}</span>
            <span class="tab-close" @click.stop="closeTab(index)">×</span>
          </div>
        </div>

        <!-- 内容区域 -->
        <div class="content-area">
          <!-- 默认标签内容（概览） -->
          <div v-if="isDefaultTabActive" class="tab-content">
            <div v-if="isDefaultTabActive">
              <component
                :is="getDefaultComponent()"
                v-if="getDefaultComponent() && isDefaultTabActive"
              />
              <!-- 如果组件未加载完成，显示加载状态 -->
              <div v-else class="loading-placeholder">
                <p>{{ $t('message.loading') }}...</p>
              </div>
            </div>
          </div>

          <!-- 其他标签页的内容 -->
          <div
            v-for="tab in openedTabs"
            :key="tab.name"
            v-show="activeTab === tab.name"
            class="tab-content"
          >
            <div class="tab-content-inner">
              <router-view v-if="activeTab === tab.name" :key="tab.name" />
            </div>
          </div>

          <!-- 为没有匹配标签页的情况提供默认显示 -->
          <div v-if="!isDefaultTabActive && openedTabs.length > 0 && !openedTabs.some(tab => tab.name === activeTab)"
               class="tab-content">
            <div class="loading-placeholder">
              <p>{{ $t('message.loading') }}...</p>
            </div>
          </div>
        </div>
      </main>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted, watch, shallowRef } from 'vue';
import { useAuthStore } from '@/stores/auth';
import { useRouter, useRoute } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { getUserMenuService } from '@/utils/menuService';
import Overview from '@/views/admin/Overview.vue';
import TeacherVerification from '@/views/admin/TeacherVerification.vue';
import AdminSettings from '@/views/admin/AdminSettings.vue';
import RoleManagement from '@/views/admin/RoleManagement.vue';
import PermissionManagement from '@/views/admin/PermissionManagement.vue';
import UserRoleManagement from '@/views/admin/UserRoleManagement.vue';

export default {
  name: 'AdminLayout',
  components: {
    Overview,
    TeacherVerification,
    AdminSettings,
    RoleManagement,
    PermissionManagement,
    UserRoleManagement
  },
  setup() {
    const { t } = useI18n();
    const router = useRouter();
    const route = useRoute();
    const authStore = useAuthStore();

    // 侧边栏折叠状态
    const sidebarCollapsed = ref(false);

    // 用户菜单
    const userMenus = ref([]);

    // 标签页管理
    const openedTabs = ref([]);
    const activeTab = ref('');

    // 动态组件管理
    const dynamicComponents = shallowRef({});

    // 展开的分类
    const expandedCategories = ref(new Set());

    // 安全获取组件的函数
    const getDynamicComponent = (name) => {
      if (!dynamicComponents.value || !dynamicComponents.value[name]) {
        return null;
      }
      return dynamicComponents.value[name];
    };

    // 状态计算
    const user = computed(() => authStore.user);

    // 切换侧边栏收起/展开状态
    const toggleSidebar = () => {
      sidebarCollapsed.value = !sidebarCollapsed.value;
    };

    // 加载用户菜单
    const loadUserMenus = async () => {
      try {
        userMenus.value = await getUserMenuService();
        // 如果API返回空菜单，使用默认菜单
        if (!userMenus.value || userMenus.value.length === 0) {
          userMenus.value = getDefaultMenus();
        }
      } catch (error) {
        console.error('Error loading user menus:', error);
        // 发生错误时使用默认菜单
        userMenus.value = getDefaultMenus();
      }
    };

    // 动态组件映射
    const componentMap = {
      '/admin/courses': () => import('@/components/admin/CourseManagement.vue'),
      '/admin/schedules': () => import('@/components/admin/ScheduleManagement.vue'),
      '/admin/bookings': () => import('@/components/admin/BookingManagement.vue'),
      '/admin/users': () => import('@/components/admin/UserManagement.vue'),
      '/admin/orders': () => import('@/components/admin/OrderManagement.vue'),
      '/admin/youbi': () => import('@/components/admin/YoubiManagement.vue'),
      '/admin/messages': () => import('@/components/admin/MessageManagement.vue'),
      '/admin/menus': () => import('@/components/admin/MenuManagement.vue'),
      '/admin/permissions': () => import('@/views/admin/PermissionManagement.vue'),
      '/admin/settings': () => import('@/components/admin/SystemSettings.vue'),
      // 权限系统相关路径
      '/admin/roles': () => import('@/views/admin/RoleManagement.vue'),
      '/admin/user-roles': () => import('@/views/admin/UserRoleManagement.vue'),
      // 教师相关路径
      '/teacher/courses': () => import('@/components/teacher/TeacherManagement.vue'),
      '/teacher/schedule': () => import('@/components/teacher/TeacherManagement.vue'),
      '/teacher/bookings': () => import('@/components/teacher/TeacherManagement.vue'),
      '/teacher/messages': () => import('@/components/teacher/TeacherManagement.vue'),
      // 家长相关路径
      '/parent/children': () => import('@/components/parent/ChildrenManagement.vue'),
      '/parent/bookings': () => import('@/components/admin/BookingManagement.vue'),
      '/parent/orders': () => import('@/components/admin/OrderManagement.vue'),
      '/parent/messages': () => import('@/components/admin/MessageManagement.vue'),
      // 助教相关路径
      '/assistant/teachers': () => import('@/components/assistant/TeacherManagement.vue'),
      '/assistant/messages': () => import('@/components/admin/MessageManagement.vue'),
      // 默认路径
      '/admin': () => import('@/views/admin/Overview.vue'),
      '/admin/dashboard': () => import('@/views/admin/Overview.vue'),
      '/admin/home': () => import('@/views/admin/Overview.vue'),
    };

    // 根据菜单URL获取对应组件
    const getComponentForMenu = async (menuUrl) => {
      try {
        if (componentMap[menuUrl]) {
          const componentModule = await componentMap[menuUrl]();
          return componentModule.default;
        } else {
          // 如果没有找到特定组件，返回默认组件
          return {
            template: `<div class="default-component"><h3>${t('message.functionNotImplemented')}</h3><p>${menuUrl} ${t('message.comingSoon')}</p></div>`,
            name: 'DefaultComponent'
          };
        }
      } catch (error) {
        console.error(`Error loading component for ${menuUrl}:`, error);
        return {
          template: `<div class="error-component"><h3>${t('message.errorLoadingComponent')}</h3><p>${menuUrl}</p></div>`,
          name: 'ErrorComponent'
        };
      }
    };

    // 动态组件加载
    const loadAndCacheComponent = async (name, menuUrl) => {
      try {
        const component = await getComponentForMenu(menuUrl);
        // 使用展开运算符更新对象，确保触发响应式更新
        dynamicComponents.value = {
          ...dynamicComponents.value,
          [name]: component
        };
      } catch (error) {
        console.error(`Error caching component for ${name}:`, error);
      }
    };

    // 处理菜单点击
    const handleMenuClick = async (menu) => {
      // 添加标签页
      if (menu.children && menu.children.length > 0) {
        // 如果是分组菜单（有子菜单），不直接打开，而是展开子菜单
        console.log("Group menu clicked:", menu.menuName);
      } else {
        // 对于概览页面路径，直接激活默认标签，不创建新标签
        if (menu.menuUrl === '/admin' || menu.menuUrl === '/admin/dashboard' || menu.menuUrl === '/admin/home') {
          switchToDefaultTab();
        } else {
          // 如果是其他叶子节点，打开标签页
          await openTab(menu.menuUrl, menu.menuName, menu);
        }
      }
    };

    // 打开新标签页
    const openTab = async (name, title, menuData = null) => {
      // 检查是否已存在标签
      let existingTab = openedTabs.value.find(tab => tab.name === name);
      if (!existingTab) {
        // 在添加标签前动态加载并缓存组件
        await loadAndCacheComponent(name, name);
        openedTabs.value.push({ name, title, menuData });
        existingTab = { name, title, menuData }; // 更新引用
      }
      activeTab.value = name;

      // 导航到对应的路由（仅当路由不同时才导航）
      if (route.path !== name) {
          await router.push({ path: name });
      }
    };

    // 检查菜单是否激活
    const isActiveMenu = (menuUrl) => {
      return activeTab.value === menuUrl;
    };

    // 检查是否是默认标签页激活
    const isDefaultTabActive = computed(() => {
      return activeTab.value === '/admin' ||
             activeTab.value === '/admin/dashboard' ||
             activeTab.value === '/admin/home' ||
             openedTabs.value.length === 0 ||
             !openedTabs.value.some(tab => tab.name === activeTab.value);
    });

    // 获取默认组件（概览）
    const getDefaultComponent = () => {
      return Overview;  // 使用已导入的 Overview 组件
    };

    // 图标映射
    const iconMap = {
      'admin-panel': '👥',
      'course': '📚',
      'schedule': '📅',
      'booking': '📝',
      'users': '👥',
      'order': '🛒',
      'youbi': '💰',
      'message': '💬',
      'menu': '📋',
      'permissions': '🔑',
      'settings': '⚙️',
      'roles': '🎭',
      'profile': '👤',
      'teaching': '🎓',
      'children': '👶',
      'teachers': '👨‍🏫',
      'dashboard': '📊',
      'adminDashboard': '📈',
      'teacherVerification': '✅',
      'adminSettings': '⚙️',
      'home': '🏠',
      'register': '📝',
      'login': '🔑',
      'logout': '🚪',
      'welcome': '👋',
      'overview': '👀',
      'teacher-panel': '👨‍🏫',
      'parent-panel': '👨 👩',
      'assistant-panel': '🤝',
      'system': '🖥️'
    };

    // 获取图标Unicode
    const getIconUnicode = (iconName) => {
      // 检查图标映射中是否有该图标
      if (iconMap[iconName]) {
        return iconMap[iconName];
      }
      // 否则根据名称模式推断图标
      if (iconName.includes('course')) return '📚';
      if (iconName.includes('sched')) return '📅';
      if (iconName.includes('book')) return '📝';
      if (iconName.includes('user') || iconName.includes('admin')) return '👥';
      if (iconName.includes('order')) return '🛒';
      if (iconName.includes('money') || iconName.includes('coin') || iconName.includes('youbi')) return '💰';
      if (iconName.includes('message') || iconName.includes('msg')) return '💬';
      if (iconName.includes('menu')) return '📋';
      if (iconName.includes('permission') || iconName.includes('auth')) return '🔑';
      if (iconName.includes('setting') || iconName.includes('config')) return '⚙️';
      if (iconName.includes('role')) return '🎭';
      if (iconName.includes('teach')) return '🎓';
      if (iconName.includes('child') || iconName.includes('kid')) return '👶';
      if (iconName.includes('teacher')) return '👨‍🏫';
      if (iconName.includes('dashboard') || iconName.includes('home')) return '🏠';
      if (iconName.includes('profile')) return '👤';

      // 默认图标
      return '📁'; // 默认文件夹图标
    };

    // 展开/收起分类
    const toggleCategory = (categoryId) => {
      if (expandedCategories.value.has(categoryId)) {
        expandedCategories.value.delete(categoryId);
      } else {
        expandedCategories.value.add(categoryId);
      }
    };

    const isExpanded = (categoryId) => {
      return expandedCategories.value.has(categoryId);
    };

    // 切换当前标签页
    const switchTab = (name) => {
      activeTab.value = name;

      // 导航到对应的路由
      router.push({ path: name });
    };

    // 切换到默认标签页（概览）
    const switchToDefaultTab = () => {
      activeTab.value = '/admin';
      router.push('/admin');
    };

    // 关闭标签页
    const closeTab = (index) => {
      const tabToRemove = openedTabs.value[index];
      openedTabs.value.splice(index, 1);

      // 如果关闭的是当前激活的标签页，切换到默认标签页
      if (tabToRemove.name === activeTab.value) {
        switchToDefaultTab();
      }
    };

    // 获取默认菜单，使用统一的菜单结构，而非区分角色面板
    const getDefaultMenus = () => {
      return [
        {
          menuId: 'user_permission_mgmt',
          menuName: '用户权限管理',
          menuIcon: 'users',
          menuUrl: '#',
          parentId: null,
          children: [
            {
              menuId: 'user_management',
              menuName: '用户管理',
              menuIcon: 'users',
              menuUrl: '/admin/users',
              parentId: 'user_permission_mgmt',
              children: []
            },
            {
              menuId: 'role_management',
              menuName: '角色管理',
              menuIcon: 'roles',
              menuUrl: '/admin/roles',
              parentId: 'user_permission_mgmt',
              children: []
            },
            {
              menuId: 'permission_management',
              menuName: '权限管理',
              menuIcon: 'permission',
              menuUrl: '/admin/permissions',
              parentId: 'user_permission_mgmt',
              children: []
            },
            {
              menuId: 'menu_management',
              menuName: '菜单管理',
              menuIcon: 'menu',
              menuUrl: '/admin/menus',
              parentId: 'user_permission_mgmt',
              children: []
            },
            {
              menuId: 'user_role_management',
              menuName: '用户角色管理',
              menuIcon: 'user-roles',
              menuUrl: '/admin/user-roles',
              parentId: 'user_permission_mgmt',
              children: []
            }
          ]
        },
        {
          menuId: 'course_schedule_mgmt',
          menuName: '课程排课管理',
          menuIcon: 'course',
          menuUrl: '#',
          parentId: null,
          children: [
            {
              menuId: 'course_management',
              menuName: '开设课程管理',
              menuIcon: 'course',
              menuUrl: '/admin/courses',
              parentId: 'course_schedule_mgmt',
              children: []
            },
            {
              menuId: 'schedule_management',
              menuName: '排课管理',
              menuIcon: 'schedule',
              menuUrl: '/admin/schedules',
              parentId: 'course_schedule_mgmt',
              children: []
            }
          ]
        },
        {
          menuId: 'business_mgmt',
          menuName: '业务管理',
          menuIcon: 'business',
          menuUrl: '#',
          parentId: null,
          children: [
            {
              menuId: 'booking_management',
              menuName: '预约管理',
              menuIcon: 'booking',
              menuUrl: '/admin/bookings',
              parentId: 'business_mgmt',
              children: []
            },
            {
              menuId: 'order_management',
              menuName: '订单管理',
              menuIcon: 'order',
              menuUrl: '/admin/orders',
              parentId: 'business_mgmt',
              children: []
            },
            {
              menuId: 'youbi_management',
              menuName: '优币管理',
              menuIcon: 'youbi',
              menuUrl: '/admin/youbi',
              parentId: 'business_mgmt',
              children: []
            },
            {
              menuId: 'message_management',
              menuName: '消息管理',
              menuIcon: 'message',
              menuUrl: '/admin/messages',
              parentId: 'business_mgmt',
              children: []
            }
          ]
        },
        {
          menuId: 'system_mgmt',
          menuName: '系统管理',
          menuIcon: 'settings',
          menuUrl: '#',
          parentId: null,
          children: [
            {
              menuId: 'system_settings',
              menuName: '系统设置',
              menuIcon: 'settings',
              menuUrl: '/admin/settings',
              parentId: 'system_mgmt',
              children: []
            },
            {
              menuId: 'system_monitor',
              menuName: '系统监控',
              menuIcon: 'monitor',
              menuUrl: '/admin/monitor',
              parentId: 'system_mgmt',
              children: []
            }
          ]
        }
      ];
    };

    // 初始化：加载用户菜单和默认标签
    onMounted(async () => {
      await loadUserMenus();
      // 如果当前路径是 /admin 相关路径
      if (route.path.startsWith('/admin')) {
        if (route.path === '/admin' || route.path === '/admin/dashboard' || route.path === '/admin/home') {
          // 设置默认标签为激活状态
          activeTab.value = route.path;
        } else {
          // 对于其他 /admin 路径，打开对应的标签页
          const menuName = getMenuNameByPath(route.path) || route.path.split('/').pop() || 'Dashboard';
          // 确保组件已加载并标签页已创建
          await openTab(route.path, menuName);
        }
      } else {
        // 对于非 /admin 路径，尝试打开与当前路由匹配的标签页
        if (route.path && route.path !== '/') {
          const menuName = getMenuNameByPath(route.path) || route.path.split('/').pop() || 'Dashboard';
          await openTab(route.path, menuName);
        }
      }
    });

    // 根据路径获取菜单名称的辅助函数
    const getMenuNameByPath = (path) => {
      // 遍历菜单寻找匹配的路径
      for (const menu of userMenus.value) {
        if (menu.menuUrl === path) {
          return menu.menuName;
        }
        if (menu.children) {
          for (const submenu of menu.children) {
            if (submenu.menuUrl === path) {
              return submenu.menuName;
            }
          }
        }
      }
      // 如果没找到匹配的菜单项，返回路径的最后一个部分
      return path.split('/').pop() || 'Dashboard';
    };

    // 监听路由变化，自动切换到对应的标签页
    watch(() => route.path, (newPath) => {
      // 如果是默认路径，直接激活默认标签，不需要创建新标签
      if (newPath === '/admin' || newPath === '/admin/dashboard' || newPath === '/admin/home') {
        // 检查当前激活的是否已经是默认标签，避免不必要的更新
        if (!isDefaultTabActive.value) {
          activeTab.value = newPath;
        }
      } else {
        // 检查是否已有对应标签页
        const existingTab = openedTabs.value.find(tab => tab.name === newPath);
        if (existingTab) {
          // 如果标签页已存在，激活该标签页（但要避免循环更新）
          if (activeTab.value !== newPath) {
            activeTab.value = newPath;
          }
        } else {
          // 路由变化时，如果是在admin路径下，自动创建对应的标签页
          if (newPath.startsWith('/admin')) {
            const menuName = getMenuNameByPath(newPath) || newPath.split('/').pop() || 'Dashboard';
            openTab(newPath, menuName);
          }
        }
      }
    });

    return {
      sidebarCollapsed,
      userMenus,
      openedTabs,
      activeTab,
      user,
      openTab,
      switchTab,
      closeTab,
      toggleSidebar,
      handleMenuClick,
      isActiveMenu,
      getIconUnicode,
      getComponentForMenu,
      dynamicComponents,
      getDynamicComponent,
      switchToDefaultTab,
      isDefaultTabActive,
      getDefaultComponent,
      toggleCategory,
      isExpanded,
      t
    };
  }
};
</script>

<style scoped>
.admin-layout {
  height: 100%; /* 让组件填满父级容器 */
  display: flex;
  flex-direction: column;
  background-color: #f0f2f5;
}

.layout-container {
  display: flex;
  flex: 1; /* 占据所有可用空间 */
  overflow: hidden; /* 防止出现滚动条 */
}

.sidebar {
  width: 256px;
  background-color: white;
  box-shadow: 2px 0 8px 0 rgba(29, 35, 41, 0.05);
  display: flex;
  flex-direction: column;
  z-index: 99;
  height: 100%;
  justify-content: flex-start; /* 确保内容在顶部对齐 */
  position: relative; /* 为切换按钮定位 */
  flex-shrink: 0; /* 防止侧边栏被压缩 */
}

.sidebar.collapsed {
  width: 60px;
  flex-shrink: 0;
}

.toggle-btn {
  position: absolute;
  top: 50%;
  right: -10px;
  transform: translateY(-50%);
  background: #1890ff;
  color: white;
  width: 20px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 0 4px 4px 0;
  cursor: pointer;
  z-index: 100;
}

.sidebar.collapsed {
  width: 60px;
}

.sidebar.collapsed .menu-text {
  display: none;
}

.sidebar.collapsed .menu-icon {
  margin-right: 0;
  font-size: 18px;
}

.menu-nav {
  padding: 0 0.5em; /* 上下为0，左右为0.5em */
  margin: 0; /* 去除所有外边距 */
  flex: 1;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  width: 100%; /* 确保占满侧边栏宽度 */
}

/* 菜单项分组样式 */
.menu-group {
  padding: 0;
  margin: 0; /* 移除所有边距 */
}

.menu-group-title {
  display: flex;
  align-items: center;
  padding: 12px 16px; /* 减少左右边距，从24px改为16px */
  color: #595959;
  font-weight: bold;
  background-color: #f5f5f5;
  border-radius: 0; /* 去除圆角使整个菜单项看起来更连贯 */
  margin: 0; /* 去除所有边距 */
  cursor: pointer;
  width: 100%; /* 确保占满侧边栏宽度 */
  box-sizing: border-box; /* 确保宽度计算包括padding */
  justify-content: space-between; /* 两端对齐使内容分布在两侧，填满宽度 */
}

.menu-group-title .menu-icon {
  margin-right: 12px;
  font-size: 16px;
}

.submenu {
  list-style: none;
  padding: 0;
  margin: 0;
  max-height: 1000px;
  overflow: hidden;
  transition: max-height 0.3s ease; /* 添加过渡动画 */
}

.submenu.hidden {
  max-height: 0; /* 当隐藏时，高度为0 */
}

.submenu .menu-item {
  padding-left: 44px; /* 为子菜单项添加更多左边距 */
  justify-content: space-between; /* 确保子菜单项也铺满宽度 */
}

.menu-nav ul {
  list-style: none;
  padding: 0;
  margin: 0;
  text-align: left; /* 文字左对齐 */
  width: calc(100% - 1em); /* 宽度为100%减去左右各0.5em的padding，共1em */
}

.menu-item {
  display: flex;
  align-items: center;
  padding: 12px 16px; /* 减少左右边距，从24px改为16px */
  color: #595959;
  text-decoration: none;
  transition: all 0.3s ease;
  border-left: 3px solid transparent;
  text-align: left;
  justify-content: space-between; /* 两端对齐，使内容分布在两端，填满宽度 */
  border-radius: 0; /* 去掉圆角，让菜单项铺满整个宽度 */
  margin: 0; /* 去除菜单项之间的所有边距 */
  width: 100%; /* 确保菜单项填满侧边栏宽度 */
  box-sizing: border-box; /* 确保宽度计算包括padding */
  white-space: nowrap; /* 防止文本换行 */
  overflow: hidden; /* 隐藏超出内容 */
  text-overflow: ellipsis; /* 超出部分显示省略号 */
}

.menu-item:hover {
  background-color: #f0f9ff;
  color: #409eff;
  border-left: 3px solid #409eff;
}

.menu-item.active {
  background-color: #ecf5ff;
  color: #409eff;
  border-left: 3px solid #409eff;
  font-weight: 500;
}

.menu-icon {
  margin-right: 8px;
  font-size: 16px;
  width: 24px;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
}

.menu-text {
  flex: 1; /* 使文本占据剩余空间 */
  font-size: 14px;
  text-align: left; /* 文字左对齐 */
  white-space: nowrap; /* 防止文本换行 */
  overflow: hidden; /* 隐藏超出内容 */
  text-overflow: ellipsis; /* 超出部分显示省略号 */
  margin-right: 8px; /* 与右侧展开图标保持一定距离 */
}

.expand-icon {
  margin-left: auto; /* 自动边距使图标推到右侧 */
  transition: transform 0.3s ease;
  font-size: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  min-width: 20px; /* 确保有足够的空间显示箭头 */
}

.expand-icon.expanded {
  transform: rotate(180deg);
}

.root-menu-title {
  display: flex;
  align-items: center;
  padding: 16px 16px; /* 减少左右边距，从24px改为16px */
  color: #1890ff;
  font-weight: bold;
  font-size: 16px;
  border-bottom: 1px solid #eee;
  margin: 0; /* 去除所有边距 */
  width: 100%; /* 确保占满侧边栏宽度 */
  box-sizing: border-box; /* 确保宽度计算包括padding */
}

.main-content {
  flex: 1; /* 占据所有可用空间 */
  display: flex;
  flex-direction: column;
  background-color: #f0f2f5;
  min-width: 0; /* Flex子项目的最小尺寸设置为0 */
  overflow: hidden; /* 防止出现不必要的滚动 */
  margin: 0;
  padding: 0;
  transition: all 0.3s ease; /* 添加过渡效果 */
}

.tabs-bar {
  display: flex;
  background-color: white;
  border-bottom: 1px solid #e8e8e8;
  overflow-x: auto;
  white-space: nowrap;
  padding: 0;
  flex-shrink: 0;
  margin: 0;
  border: none;
  box-shadow: none;
  min-height: 40px;
}

.tab-item {
  padding: 8px 20px;
  background-color: #fafafa;
  border: 1px solid #e8e8e8;
  border-bottom: none;
  border-top-left-radius: 4px;
  border-top-right-radius: 4px;
  border-top: 1px solid #e8e8e8;
  margin-right: 4px;
  cursor: pointer;
  position: relative;
  display: inline-flex;
  align-items: center;
  margin: 0;
  line-height: normal;
}

.tab-item.active {
  background-color: white;
  border-bottom: 1px solid white;
  color: #1890ff;
  font-weight: 500;
  margin-bottom: -1px;
}

.tab-close {
  margin-left: 8px;
  width: 18px;
  height: 18px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  font-size: 12px;
}

.tab-close:hover {
  background-color: #ccc;
  color: white;
}

.content-area {
  flex: 1; /* 占据所有可用空间 */
  overflow-y: auto;
  padding: 16px; /* 减少内边距，从24px改为16px */
  background-color: #fff;
  border: 1px solid #e8e8e8;
  border-top: none;
  border-top-left-radius: 0;
  border-top-right-radius: 0;
  min-height: 0; /* 允许内容区域在小空间内滚动 */
  overflow: auto;
  margin: 0;
}

.tab-content {
  height: 100%;
}

.tab-content-inner {
  height: 100%;
}

.loading-placeholder {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  min-height: 200px;
  color: #909399;
}

.default-component, .error-component {
  padding: 20px;
  text-align: center;
  color: #909399;
}

@media (max-width: 768px) {
  .sidebar {
    width: 200px;
  }
}
</style>